package com.c2b.algorithm.leetcode.jzoffer;

/**
 * <a href="https://www.nowcoder.com/practice/f9f78ca89ad643c99701a7142bd59f5d?tpId=13&tqId=2273171&ru=%2Fpractice%2Fd0267f7f55b3412ba93bd35cfa8e8035&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking&sourceUrl=">删除链表的节点</a>
 * <p>
 * 给定单向链表的头指针和一个要删除的节点的值，定义一个函数删除该节点。返回删除后的链表的头节点。
 * <p>
 * 1.此题对比原题有改动<br>
 * 2.题目保证链表中节点的值互不相同<br>
 * 3.该题只会输出返回的链表和结果做对比，所以若使用 C 或 C++ 语言，你不需要 free 或 delete 被删除的节点<br>
 * </p>
 *
 * @author c2b
 * @since 2023/3/8 16:58
 */
public class JzOffer0018DeleteNode_S {

    public ListNode deleteNode(ListNode head, int val) {
        if (head == null) {
            return null;
        }
        // 加个头节点
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode currNode = dummy;
        while (currNode.next != null) {
            if (currNode.next.val != val) {
                currNode = currNode.next;
            } else {
                currNode.next = currNode.next.next;
            }
        }
        return dummy.next;
    }

    public static void main(String[] args) {
        // 2,5,1,9
        ListNode listNode = new ListNode(2);
        listNode.next = new ListNode(5);
        listNode.next.next = new ListNode(1);
        listNode.next.next.next = new ListNode(9);
        JzOffer0018DeleteNode_S jzOffer0018DeleteNode = new JzOffer0018DeleteNode_S();
        ListNode listNode1 = jzOffer0018DeleteNode.deleteNode(listNode, 9);
        while (listNode1 != null) {
            System.out.println(listNode1.val);
            listNode1 = listNode1.next;

        }
    }
}
